package kassiopeia.agent.repository;

import java.io.File;
import java.io.IOException;
import kassiopeia.commons.exception.RepositoryException;
import kassiopeia.commons.model.Coordinates;

public class LocalRepository implements Repository {

	private File repositoryDir;

	public LocalRepository(String repositoryDir) {
		try {
			this.repositoryDir = new File(repositoryDir);
			prepareRepository();
		} catch(Exception exception) {
			throw new RepositoryException("Can't configure local repository", exception);
		}
	}

	@Override
	public File getPluginJar(Coordinates coords) {
		File pluginFile = new File(repositoryDir, buildJARName(coords));
		if(pluginFile.isFile()) {
			return pluginFile;
		}
		return null;
	}

	@Override
	public String getLocation() {
		return repositoryDir.getAbsolutePath();
	}

	private void prepareRepository() throws IOException {
		if(repositoryDir.isDirectory())
			return ;

		if(!repositoryDir.mkdirs()) {
			throw new IOException("Can't create repository at location: " + repositoryDir.getAbsolutePath());
		}
	}

	private String buildJARName(Coordinates coords) {
		return coords.getGroupId() + "." + coords.getPluginId() + "-" + coords.getVersion() + ".jar";
	}
}
